using System;
using UnityEngine;

public class BallDragger : MonoBehaviour
{
	public LayerMask layermask;

	public Action<BallDraggerData> dragBegin;

	public Action<BallDraggerData> dragEnd;

	public Action<BallDraggerData> drag;

	private BallDraggerData m_DraggerData = default(BallDraggerData);

	private bool m_Drag;

	private void Awake()
	{
	}

	private void Update()
	{
		if (Input.touchSupported)
		{
			ProcessTouchEvents();
		}
		else
		{
			ProcessMouseEvents();
		}
	}

	private void ProcessMouseEvents()
	{
		if (Input.GetMouseButtonDown(0))
		{
			BeginEvent(UnityEngine.Input.mousePosition);
		}
		else if (Input.GetMouseButton(0))
		{
			ProcessEvent(UnityEngine.Input.mousePosition);
		}
		else if (Input.GetMouseButtonUp(0))
		{
			EndEvent(UnityEngine.Input.mousePosition);
		}
	}

	private void ProcessTouchEvents()
	{
		if (UnityEngine.Input.touchCount > 0)
		{
			Touch touch = UnityEngine.Input.GetTouch(0);
			if (touch.phase == TouchPhase.Began)
			{
				BeginEvent(touch.position);
			}
			else if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
			{
				ProcessEvent(touch.position);
			}
			else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
			{
				EndEvent(touch.position);
			}
		}
	}

	private void BeginEvent(Vector2 position)
	{
		m_DraggerData.Position = position;
		m_DraggerData.DeltaPosition = Vector2.zero;
		if (RayCast(position) && dragBegin != null)
		{
			dragBegin(m_DraggerData);
			m_Drag = true;
		}
	}

	private void ProcessEvent(Vector2 position)
	{
		m_DraggerData.DeltaPosition = position - m_DraggerData.Position;
		m_DraggerData.Position = position;
		if (m_DraggerData.DeltaPosition.sqrMagnitude != 0f && m_Drag && drag != null)
		{
			drag(m_DraggerData);
		}
	}

	private void EndEvent(Vector2 position)
	{
		m_DraggerData.Position = Vector2.zero;
		m_DraggerData.DeltaPosition = Vector2.zero;
		if (m_Drag && dragEnd != null)
		{
			dragEnd(m_DraggerData);
			m_Drag = false;
		}
	}

	private bool RayCast(Vector2 p)
	{
		Vector3 origin = Pools.SceneCamera.ScreenToWorldPoint(p);
		Vector3 down = Vector3.down;
		Ray ray = new Ray(origin, down);
		if (Physics.SphereCast(ray, Pools.CueBall.GetRadius(), out RaycastHit hitInfo, 1000f, 1 << layermask.value) && hitInfo.collider.gameObject.GetInstanceID() == base.gameObject.GetInstanceID())
		{
			return true;
		}
		return false;
	}
}
